// import {getSongDetail, getSongLyric,getSingerDetail} from '../service/api_player'
import {parseLyric} from '../utils/parse-lyric'
import {HYEventStore} from 'hy-event-store'
const db = wx.cloud.database()
// const audioContext = wx.createInnerAudioContext()
const audioContext = wx.getBackgroundAudioManager()

wx.setInnerAudioOption({
  mixWithOther: true,
  obeyMuteSwitch: false,
  success:function(e){
    console.log('play');
  },
  fail:function(){
    console.log('fail');
  }
})

const playerStore = new HYEventStore({
  state:{
    isFirstPlay:true,
    isStoping: false,
    id:0,
    currentSong:{},
    durationTime:0,
    lyricInfos:[],

    title:"",
    coverImgUrl:"",
    webUrl:"",

    currentTime:0,
    currentLyricIndex: 0,
    currentLyricText:"",

    isPlaying:false,
    //0 循环播放 1 单曲循环 2 随机播放
    playModeIndex: 0 ,
    playListSongs:[] ,
    playListIndex: 0,

    singerPic:"",
    singerId:0,
    songId: 0,

    moveDistance: 0,
    searchId:""
  },
  actions:{
    playMusicWithSongIdAction(ctx, { id ,isRefresh = false }){
      if(ctx.id == id && !isRefresh){
        this.dispatch("changeMusicPlayStatusAction", true)
        return
      } 
      ctx.id = id
      //修改播放的状态
      ctx.isPlaying = true
      ctx.currentSong = {}
      ctx.durationTime = 0
      ctx.lyricInfos = []
      ctx.currentTime = 0
      ctx.currentLyricIndex = 0
      ctx.currentLyricText = ""
      ctx.searchId = ""
      //请求歌曲详情歌词
      db.collection('songs').where({id:id * 1}).get().then(res =>{
        console.log(res.data)         
          ctx.currentSong = res.data
          ctx.searchId = res.data[0]._id
          ctx.durationTime = res.data[0].dt

          ctx.title = res.data[0].name
          ctx.coverImgUrl = res.data[0].al.picUrl
          ctx.webUrl = res.data[0].al.picUrl
       
          ctx.songId = res.data[0].id
          const lyricString = res.data[0].lrc.lyric
          const lyric = parseLyric(lyricString)
          ctx.lyricInfos = lyric

              //歌曲播放次数增加
          const _ = db.command
          db.collection('songs').doc(ctx.searchId).update({
            data:{
              playCount:_.inc(1)
            },
            success:function(res){
              console.log('歌曲播放次数增加1');
            }
          })
      })

      

      // audioContext.title = ctx.id
      // audioContext.coverImgUrl =  ctx.coverImgUrl
      // audioContext.webUrl = ctx.webUrl

      //播放对应id的歌曲
      audioContext.stop()
      audioContext.src= `https://music.163.com/song/media/outer/url?id=${id}.mp3`
      audioContext.title = '正在播放音乐'
      audioContext.autoplay = true
      
      //监听audioContext一些事件
      if(ctx.isFirstPlay){
        this.dispatch("setUpAudioContextListenerAction")
        //不要监听太多次了
        ctx.isFirstPlay = false
      }
    },

    changeMoveDistance(ctx, height) {
      ctx.moveDistance = height
    },

    setUpAudioContextListenerAction(ctx){

        audioContext.onCanplay(()=>{
          audioContext.play()
        })

        audioContext.onTimeUpdate(()=>{
          //获取当前时间
          const currentTime = audioContext.currentTime * 1000

          //根据当前时间修改currentTime/sliderTime
          ctx.currentTime = currentTime

          //根据当前时间区查找播放的歌词
          if(!ctx.lyricInfos.length) return 
          for(let i = 0;i < ctx.lyricInfos.length;i++){
            const lyricInfo = ctx.lyricInfos[i]
            if(currentTime < lyricInfo.time){
              const currentIndex = i - 1
              if(ctx.currentLyricIndex !== currentIndex){
                const currentLyricInfo = ctx.lyricInfos[currentIndex]

                ctx.currentLyricIndex = currentIndex
                if(currentLyricInfo){
                  ctx.currentLyricText = currentLyricInfo.text
                }
    
              }      
              break
            }
          }
        })

        //监听歌曲播放完成
        audioContext.onEnded(()=>{
          this.dispatch("changeNewMusicAction")
        })

        //监听音乐暂停/播放
        //播放
        audioContext.onPlay(( ) => {
          ctx.isPlaying =  true
        })
        //暂停
        audioContext.onPause(()=>{
          ctx.isPlaying = false
        })

        audioContext.onStop(()=>{
          ctx.isPlaying = false
          ctx.isStoping = true
        })
    },

    changeMusicPlayStatusAction(ctx,isPlaying = true){
      ctx.isPlaying = isPlaying
      if(ctx.isPlaying && ctx.isStoping){
        audioContext.src= `https://music.163.com/song/media/outer/url?id=${ctx.id}.mp3`
        audioContext.title = ctx.currentSong.name
      }
      if(ctx.isPlaying){
        audioContext.play()
      }else{
        audioContext.pause()
      }
      // if(ctx.isStoping){
      //   audioContext.seek(ctx.currentTime)
      //   ctx.isStoping = false
      // }
    },

    changeNewMusicAction(ctx ,isNext = true){
      //获取索引
      let index = ctx.playListIndex

      //根据不同的播放模式，获取下一首歌的索引
      switch(ctx.playModeIndex){
        case 0: 
          index = isNext ? index + 1 : index - 1
          if(index === -1) index = ctx.playListSongs.length - 1
          if(index === ctx.playListSongs.length) index = 0
          break
        case 1: 
          break
        case 2: 
          index = Math.floor(Math.random() * ctx.playListSongs.length)
          break
      }
      
      //获取歌曲
      let currentSong = ctx.playListSongs[index]
      if(!currentSong) {
        currentSong = ctx.currentSong
      }
      else{
        ctx.playListIndex = index
      }

      //播放新的歌曲
      this.dispatch("playMusicWithSongIdAction",{id : currentSong.id ,isRefresh : true})
    },
    selectNewMusicAction(ctx, index) {
      // 获取歌曲
      let currentSong = ctx.playListSongs[index]
      if (!currentSong) {
        currentSong = ctx.currentSong
      } else {
        // 记录最新的索引
        ctx.playListIndex = index
      }

      // 4.播放新的歌曲
      this.dispatch("playMusicWithSongIdAction", {
        id: currentSong.id,
        isRefresh: true
      })

    }
  }
})

export{
  audioContext,
  playerStore
}